package baiqitun.stupro.common.service.system.impl;

import baiqitun.stupro.common.entity.impl.SysFile;
import baiqitun.stupro.common.exception.support.DisabledException;
import baiqitun.stupro.common.mapper.SysFileMapper;
import baiqitun.stupro.common.service.EntityEnabledChecker;
import baiqitun.stupro.common.service.system.SysFileService;
import baiqitun.stupro.common.service.support.MyServiceImpl;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 文件表 服务实现类
 * </p>
 *
 * @author kedaji
 * @since 2020-04-20
 */
@Slf4j
@Service
public class SysFileServiceImpl extends MyServiceImpl<SysFileMapper, SysFile> implements SysFileService, EntityEnabledChecker<SysFile> {
    @Value("${system.upload-path}")
    private String uploadPath;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysFile file, InputStream is) {
        File tempFile = null;
        BufferedInputStream bis = null;
        try {
            // 先创建临时文件
            tempFile = FileUtil.createTempFile("stupro_", null, new File(uploadPath), false);
            FileUtil.writeFromStream(is, tempFile);
            super.save(file);
            // 如果在保存数据的时候没有发生异常，再将临时文件保存到磁盘
            File newFile = FileUtil.touch(uploadPath, file.getId());
            bis = FileUtil.getInputStream(tempFile);
            FileUtil.writeFromStream(bis, newFile);
        } finally {
            if (bis != null){
                try {
                    bis.close();
                } catch (IOException e) {
                    // 不可能到这里
                }
            }
            // 操作后将临时文件删掉
            FileUtil.del(tempFile);
        }
    }

    @Override
    public void checkDisabled(String id, DisabledException e) {

    }

    @Override
    public SysFile getEnabledEntity(String id, DisabledException e) {
        return null;
    }
}
